import { Component, OnInit, OnDestroy } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router'
import { NzMessageService } from 'ng-zorro-antd'

import { GroupNewBaseComponent } from './base/base.component'
import { GroupNewUserComponent } from './user/user.component'
import { GroupStoreService } from './group-store.service'
import { GroupService } from '../group.service'
import { PageService } from '@shared/services/page.service'
import { INewPageColumn } from '@shared/interfaces/common'
import { ComWindow } from '@shared/classes/ComWindowClass'
import { encryptPassword } from 'app/utils/helpers'
import { User } from '@shared/interfaces/user'
import { I18NService } from '@core'

@Component({
  selector: 'app-group-new',
  templateUrl: './new.component.html',
})
export class GroupNewComponent implements OnInit, OnDestroy {
  pages: INewPageColumn[] = []

  constructor(
    public msgSrv: NzMessageService,
    public router: Router,
    public route: ActivatedRoute,
    private groupStore: GroupStoreService,
    private groupService: GroupService,
    private pageService: PageService,
    private i18n: I18NService,
  ) { }

  ngOnInit() {
    this.initColumns()
  }

  ngOnDestroy() {
    this.groupStore.reset()
  }

  initColumns() {
    this.pages = [
      {
        component: new ComWindow(GroupNewBaseComponent, { title: 'GENERAL.INFO.OTHER.BASIC_CONFIG' }),
      },
      {
        component: new ComWindow(GroupNewUserComponent, { title: 'GENERAL.INFO.OTHER.USERS' }),
      }
    ]
  }

  submit(): void {
    const group = this.groupStore.value
    // encrypt user password
    group.users.forEach( (user: User) => {
      user.password = encryptPassword(user.password)
    })
    this.groupService.create(group).subscribe(data => {
      // WORKAROUND
      this.pageService.triggerGuardAlive(false) // 使路由守卫失效
      this.groupStore.reset()
      this.msgSrv.success(this.trans('GENERAL.NOTIFICATION.CREATE_SUCCESS'))
      this.router.navigate(['..'], { relativeTo: this.route})
      // WHEN BACKEND RETURN DATA USE BELOW HANDLER
      // if (Object.keys(data).length !== 0) {
      //   /* 创建成功 */
      //   this.pageService.triggerGuardAlive(false) // 使路由守卫失效
      //   this.groupStore.reset()
      //   this.msgSrv.success(this.trans('GENERAL.NOTIFICATION.CREATE_SUCCESS'))
      //   this.router.navigate(['..'], { relativeTo: this.route})
      // } else {
      //   /* 创建失败 */
      //   this.msgSrv.error(this.trans('GENERAL.NOTIFICATION.CREATE_FAIL'))
      // }
    })
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
